namespace CRM_Perf_BenchMark
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.WebTesting;
    using System.Net;
    using System.Text;
    using System.Xml;
    
	/// <summary>
	/// 1. Starts at Service homepage
	/// 2. Click on Cases
	/// 3. Select Active Cases view
	/// 4. Add random string of two characters in look for textbox and click find
	/// 5. Double click a case
	/// 6. Select Assign from Actions menu
	/// 7. Select Assign to another user or queue radio button
	/// 8. Select a user from the search menu
	/// 9. Click OK
	/// 10. Click Save & Close
	/// </summary>
    
    public class AssignServiceCase : CrmWebTest
    {
        public void AssignServiceCase_PreWebTest(object sender, PreWebTestEventArgs e)
        {
			EntityRequest er = new EntityRequest();
			er.Type = EntityNames.Users;
			er.ReturnAs = EntityNames.Users;
			er.ParentID = EntityManager.Instance.OrgId;

			System.Collections.Hashtable Props = new System.Collections.Hashtable();
            
            if (e.WebTest.Context.ContainsKey("UserRole"))
            {
                Props.Add("role", e.WebTest.Context["UserRole"]);
            }

            EntityRequest IncidentEr = new EntityRequest();
            IncidentEr.Type = EntityNames.Incidents;
            IncidentEr.ParentID = Guid.NewGuid();
            IncidentEr.ReturnAs = EntityNames.Incidents;

            Props.Add(EntityNames.Incidents, new EntityRequest[] { IncidentEr });

            er.Props = Props;

            System.Collections.Hashtable Entities = EntityManager.Instance.GetEntities(er);

			user = (CRMEntity)Entities[EntityNames.Users];
			incident = (CRMEntity)Entities[EntityNames.Incidents];
                        
            e.WebTest.UserName = user["domainName"];
            e.WebTest.Password = user["userpassword"];

            crmServer = user["CrmServer"];
            tokenKey = EntityManager.Instance.ReadTokenKey(user["organizationid"]);

            user2 = EntityManager.Instance.GetNextUser(); 
        }
        
        public void AssignServiceCase_PostWebTest(object sender, PostWebTestEventArgs e)
        {
            try
            {
                if (success)
                {
                    string newIncidentId = incident[EntityIDNames.Incident];
                    if (newIncidentId != null)
                    {
                        Guid g = EntityManager.Instance.GetOwnerGuid(new Guid(user2[EntityIDNames.User]), new Guid(user2["OrganizationId"]));
                        EntityManager.Instance.AddEntity(EntityNames.Incidents, g, new string[] { "OwnerID", "IncidentID", "Title", "EntityManagerOwningUser" }, new string[] { user2["systemuserid"], incident[EntityIDNames.Incident], incident["Title"], g.ToString() });
                    }
                }
            }
            catch (System.FormatException fe)
            {
                System.Diagnostics.Trace.WriteLine("Failed to convert bogus data into Guid. " + fe.ToString());
            }
            finally
            {
                EntityManager.Instance.FreeEntity(incident);
                EntityManager.Instance.FreeEntity(user);
                EntityManager.Instance.FreeEntity(user2);
            }
        }

        private void AssignServiceCase_ValidateResponse(object sender, ValidationEventArgs e)
        {
            if (e.Response.StatusCode == HttpStatusCode.OK)
            {
                e.IsValid = true;
                success = true;
            }
            else
            {
                e.IsValid = false;
                success = false;
            }
        }

        public AssignServiceCase()
        {
            WebRequest.RegisterPrefix("crm", new crmRequestFactory());

            //GetContextHtml_Helper.Subject(out ctxt, out ctxt_formXml, out ctxt_formSubmitId);
            string random = Utils.GetRandomString(2, 2);
            gridXml = GridXmlHelper.IncidentPageView(-1, activeIncidentView, null);
            gridXml2 = GridXmlHelper.IncidentSearchView(-1, searchIncidentView, random, null);
            gridXml3 = GridXmlHelper.IncidentPageSearchViewRefresh(-1, searchIncidentView, random, null);

            this.Proxy = null;
            PreWebTest += new EventHandler<PreWebTestEventArgs>(AssignServiceCase_PreWebTest);
            PostWebTest += new EventHandler<PostWebTestEventArgs>(AssignServiceCase_PostWebTest);
        }

        public override IEnumerator<WebTestRequest> GetRequestEnumerator()
        {
            incidentId = new Guid(incident["incidentid"]);
            AppGridWebService.AppGridWebService agws;
            WebTestRequest wtr;

			this.BeginTransaction("NavServiceCaseHomepage");

            cs_home_cases_aspx casesHome = new cs_home_cases_aspx(user);
            yield return (casesHome);

			this.EndTransaction("NavServiceCaseHomepage");

            if (ConfigSettings.Default.alltasks == true)
            {
                this.BeginTransaction("NavActiveServiceCases");

                agws = new AppGridWebService.AppGridWebService();
                wtr = null;
                try { agws.Reset(gridXml, gridId); }
                catch (crmException x)
                {
                    wtr = (CrmRequest)x.wtr;
                    wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                    string urlPath = wtr.Url.Remove(0, crmServer.Length);
                    urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                    rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctokentimestamp";
                    headerItem.Value = rpcInfo.timeStamp.ToString();
                    wtr.Headers.Add(headerItem);
                    headerItem = new WebTestRequestHeader();
                    headerItem.Name = "crmwrpctoken";
                    headerItem.Value = rpcInfo.token;
                    wtr.Headers.Add(headerItem);
                    wtr.Method = "Post";
                }
                yield return (wtr);

                this.EndTransaction("NavActiveServiceCases");
            }

			this.BeginTransaction("SearchServiceCases");

			agws = new AppGridWebService.AppGridWebService();
			wtr = null;

			try { agws.Reset(gridXml2, gridId); }
			catch (crmException x)
			{
				wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
			}
			yield return (wtr);

			this.EndTransaction("SearchServiceCases");

            this.BeginTransaction("OpenServiceCase");

            // simulate double clicking of Case
            cs_cases_edit_aspx dp = new cs_cases_edit_aspx(user);
            dp.id = incidentId;
            yield return (dp);

            referer = dp.lastResponse.ResponseUri.AbsoluteUri;

            _forms_FormScript_js_aspx fs = new _forms_FormScript_js_aspx(user);
            fs.etc = 112;
            fs.FormType = "main";
            fs.FormName = "crmForm";
            headerItem = new WebTestRequestHeader("referer", referer);
            fs.Headers.Add(headerItem);
            yield return (fs);

            this.EndTransaction("OpenServiceCase");

            this.BeginTransaction("AssignServiceCase");

            _grid_cmds_dlg_assignqueue_aspx aq = new _grid_cmds_dlg_assignqueue_aspx(user);
            aq.iObjtype = 112;
            aq.iTotal = 1;
            aq.sQType = 1;
            aq.FromForm = 1;
            aq.uid = incidentId;
            yield return (aq);

            _controls_lookup_lookupsingle_aspx ls = new _controls_lookup_lookupsingle_aspx(user);
            ls.Class = "BasicOwner";
            ls.objecttypes = "8,2020";
            ls.browse = 0;
            ls.ShowNewButton = 1;
            ls.ShowPropButton = 1;
            ls.DefaultType = 0;
            yield return (ls);

            dp = new cs_cases_edit_aspx(user);
            // QueryString Parameters
            dp.id = incidentId;

            // Form Parameters
            dp.crmFormSubmitXml = "<incident></incident>";

            rpcInfo = Utils.GenerateWRPCToken(cs_cases_edit_aspx.url, user, tokenKey);
            dp.CRMWRPCToken = rpcInfo.token;
            dp.CRMWRPCTokenTimeStamp = rpcInfo.timeStamp;
            dp.crmFormSubmitMode = 49;
            dp.crmFormSubmitId = incidentId;
            dp.crmFormUserModified = true;
            dp.crmFormSubmitObjectType = 112;
            dp.crmFormSubmitOnline = 1;
            dp.crmFormSubmitSecurity = 852023;
            dp.assignOwnerId = new Guid(user2["systemuserid"]);
            dp.assignOwnerType = 8;
            dp.ValidateResponse += this.AssignServiceCase_ValidateResponse;
            yield return (dp);

            agws = new AppGridWebService.AppGridWebService();
            wtr = null;
            try { agws.Refresh(gridXml3); }
            catch (crmException x)
            {
                wtr = (CrmRequest)x.wtr;
                wtr.Url = Utils.ReplaceServerName(wtr.Url, user);

                string urlPath = wtr.Url.Remove(0, crmServer.Length);
                urlPath = urlPath.Remove(0, user["organizationName"].Length + 1);

                rpcInfo = Utils.GenerateWRPCToken(urlPath, user, tokenKey);

                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctokentimestamp";
                headerItem.Value = rpcInfo.timeStamp.ToString();
                wtr.Headers.Add(headerItem);
                headerItem = new WebTestRequestHeader();
                headerItem.Name = "crmwrpctoken";
                headerItem.Value = rpcInfo.token;
                wtr.Headers.Add(headerItem);
                wtr.Method = "Post";
            }
            yield return (wtr);

            this.EndTransaction("AssignServiceCase");
        }
        private string gridXml;
        private string gridXml2;
        private string gridXml3;
        private static string gridId = "crmGrid";
        bool success;

        private const string newIdMarker = @"SetQueryString(location.href,""id"",""";

        private CRMEntity user;
        private CRMEntity user2;
        private CRMEntity incident;
        private string tokenKey;
        private string crmServer;

        private Guid incidentId;

        private static string searchIncidentView = "D95D47EF-4A1D-479E-9065-B9CEA0089048";
		private static string activeIncidentView = "00000000-0000-0000-00AA-000010001032";

        private WRPCInfo rpcInfo;
        private WebTestRequestHeader headerItem;
        private string referer;
    }
}